<template>
  <a-form ref="formRef" v-bind="$attrs" v-on="$attrs">
    <template v-if="isAllPageFormItem">
      <a-row :gutter="gutter">
        <slot></slot>
      </a-row>
    </template>
    <slot v-else></slot>
  </a-form>
</template>
<script>
  import { nextTick, ref, provide } from 'vue'
  import { useGutter } from '@/hooks/usePageForm'
  export default {
    props: {
      gutter: {
        type: [Object, Number],
        default: useGutter(),
      },
    },
    setup(props, { slots, attrs }) {
      const _default = slots.default
      const instanceList = _default()
      // 判断子元素是否全部都是 PageFormItem
      let isAllPageFormItem = ref(true)
      instanceList.forEach((item) => {
        if (item.type.__name != 'page-form-item') {
          isAllPageFormItem = false
        }
      })
      provide('formRules', attrs.rules || [])
      provide('formDisabled', attrs.disabled)
      const formRef = ref()
      const validate = (callback, scrollError = true) => {
        scrollError && scrollErrorFn()
        formRef.value.validate((error) => {
          callback(error, scrollErrorFn)
        })
      }
      const validateField = (field, callback) => {
        formRef.value.validateField(field, callback)
      }
      const resetFields = (field) => {
        formRef.value.resetFields(field)
      }
      const clearValidate = (field) => {
        formRef.value.clearValidate(field)
      }
      const setFields = (data) => {
        formRef.value.setFields(data)
      }

      const scrollErrorFn = () => {
        nextTick(() => {
          setTimeout(() => {
            const errItem = document.getElementsByClassName(`arco-form-item-error`)
            const errFirst = errItem[0]
            if (errFirst) {
              errFirst.scrollIntoView()
            }
          }, 0)
        })
      }

      return {
        validate,
        validateField,
        resetFields,
        clearValidate,
        setFields,
        formRef,
        useGutter,
        isAllPageFormItem,
      }
    },
  }
</script>
